<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <span>分类列表</span>
      </template>
      <!-- 树形组件 -->
      <el-tree :data="treeData" :props="defaultProps" default-expand-all>
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <span>{{ node.label }}</span>
            <div class="actions">
              <el-button @click="openEditDialog(node,data)" icon="edit" type="primary" link size="small">编辑</el-button>
              <el-button @click.stop="openInsertDialog(node,data)" icon="CirclePlus" type="primary" link size="small">
                添加
              </el-button>
              <el-button @click="handleRemove(node,data)" icon="delete" type="primary" link size="small">删除</el-button>
            </div>
          </div>
        </template>
      </el-tree>
    </el-card>
    <!-- 添加分类dialog -->
    <el-dialog v-model="insert_dialog_visible" title="添加分类">
      <el-form ref="insert_form_ref" :rules="rules" :model="insert_form" status-icon label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="insert_form.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="insert_dialog_visible = false">取消</el-button>
          <el-button type="primary" @click.stop="handleInsert(insert_form_ref)">添加</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑分类dialog -->
    <el-dialog v-model="edit_dialog_visible" title="编辑分类">
      <el-form ref="edit_form_ref" :rules="rules" :model="edit_form" status-icon label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="edit_form.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="edit_dialog_visible = false">取消</el-button>
          <el-button type="primary" @click.stop="handleEdit(edit_form_ref)">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Kindof from '@/api/kind';
import { ref, onMounted, reactive } from 'vue';

// 树形结构数据
let treeData = ref([]);

// 对齐组件树的显示属性
const defaultProps = {
  children: 'children',
  label: 'name',
}
// 表单验证规则
let rules = reactive({
  name: [{ required: true, message: '请输入分类名称！', trigger: 'blur' }]
});

onMounted(async () => {
  let { status, msg, data } = await Kindof.all({ type: 'tree' });
  if (status) {
    treeData.value = [{ id: 0, name: '全部分类', children: data }];
  }
});

// 获取Form组件实例
let insert_form_ref = ref();
// 添加dialog状态
let insert_dialog_visible = ref(false);
// 添加Model
let insert_form = reactive({ name: '' });

// 当前节点的data
let current_data = ref({});


// 打开添加dialog
let openInsertDialog = (node, data) => {
  // 缓存data数据
  current_data.value = data;

  insert_dialog_visible.value = true;
}

// 添加分类
let handleInsert = (formEl) => {
  formEl.validate(async (valid) => {
    if (valid) {
      let { status, msg, data } = await Kindof.add({ ...insert_form, parent_id: current_data.value.id });
      if (status) {
        // 新的节点数据
        const newChild = { ...data, ...insert_form, children: [] };

        if (!current_data.value.children) {
          current_data.value.children = []
        }
        current_data.value.children.push(newChild);
        treeData.value = [...treeData.value];
        // 关闭添加dialog
        insert_dialog_visible.value = false;
      }
    }
  });
}

// 获取Form组件实例
let edit_form_ref = ref();
// 添加dialog状态
let edit_dialog_visible = ref(false);
// 添加Model
let edit_form = ref({ name: '' });
// 当前节点的node
let current_node = ref({});

// 打开编辑dialog
let openEditDialog = (node, data) => {
  // 缓存node数据
  current_node.value = node;
  // 还原表单
  edit_form.value = { ...data };
  // 打开dialog
  edit_dialog_visible.value = true;
}

// 编辑分类
let handleEdit = (formEl) => {
  formEl.validate(async (valid) => {
    if (valid) {
      let { status, msg } = await Kindof.edit({ ...edit_form.value });
      if (status) {
        // 更新DOM
        current_node.value.data = { ...edit_form.value };
        // 关闭dialog
        edit_dialog_visible.value = false;
      }
    }
  });
};

// 删除分类
let handleRemove = (node, data) => {
  ElMessageBox.confirm('此操作将永久删除该分类，确定要继续吗？', { type: 'warning' })
    .then(async () => {
      let { status, msg } = await Kindof.remove({ id: data.id });
      if (status) {
        // 更新DOM
        const parent = node.parent
        const children = parent.data.children || parent.data
        const index = children.findIndex((d) => d.id === data.id)
        children.splice(index, 1);
        treeData.value = [...treeData.value];
        // 消息提示
        ElMessage.success(msg);
      } else {
        ElMessage.error(msg);
      }
    })
    .catch(() => {
      ElMessage.info('取消成功！');
    });
}
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
